package com.yupi.yu_picture.api.imageSearch.sub;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.yu_picture.api.imageSearch.model.ImageSearchResult;
import com.yupi.yu_picture.exception.BusinessException;
import com.yupi.yu_picture.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GetImageList {
    /**
     * 根据相似图片页面地址提取所有相似图片的地址
     * @param url 1.搜图结果地址--》2.整个页面地址--》3.提取页面
     * @return
     */
    public static List<ImageSearchResult> getImageList(String url){
        try {
            HttpResponse response = HttpUtil.createGet(url).execute();
            int statusCode = response.getStatus();
            String body = response.body();//响应体都是json格式的字符串
            if (statusCode == 200) {
                //解析json数据并处理：
                return processResponse(body);
            } else {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
        }catch (Exception e){
            log.error("获取图片列表失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取图片列表失败");
        }

    }

    private static List<ImageSearchResult> processResponse(String responseBody) {
        //解析响应对象
        JSONObject jsonObject = new JSONObject(responseBody);
        if (!jsonObject.containsKey("data")){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"为获取到图片列表");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (!data.containsKey("list")){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"为获取到图片列表");

        }
        JSONArray list = data.getJSONArray("list");
        return JSONUtil.toList(list,ImageSearchResult.class);
    }


    public static void main(String[] args) {
        String url="https://graph.baidu.com/ajax/pcsimi?carousel=503&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&inspire=general_pc&limit=30&next=2&render_type=card&session_id=9456498466888606439&sign=126e5e97cd54acd88139901744274855&tk=b9af4&tpl_from=pc";
        List<ImageSearchResult> imageList = getImageList(url);
        System.out.println(imageList);
    }
}
